"use client";
import {
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Table,
  TreeSelect,
  Switch,
  App,
} from "antd";
import React, { useEffect, useState } from "react";
import { menuTableColumns, getIconByName, IconMap } from "./tools";
import { system } from "@/forent-api/api";

const { Option } = Select;
const { SHOW_PARENT } = TreeSelect;

const menuTypeOptions = [
  { label: "菜单", value: "menu" },
  { label: "按钮", value: "button" },
];

const MenuPage: React.FC = () => {
  const [menuList, setMenuList] = useState<any[]>([]);
  const [menuTree, setMenuTree] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [modalTitle, setModalTitle] = useState<string>("添加菜单");
  const [iconPreview, setIconPreview] = useState<React.ReactNode>(null);
  const [permissionOptions, setPermissionOptions] = useState<any[]>([]);
  const [form] = Form.useForm();
  const { message, modal } = App.useApp();

  // 加载菜单数据和权限数据
  useEffect(() => {
    fetchMenuList();
    fetchPermissions();
  }, []);

  // 获取菜单列表
  const fetchMenuList = async () => {
    setLoading(true);
    try {
      const res = await system.getMenuAll();
      console.log("res==========>>>>", res)
      setMenuList(res.data);

      // 构建TreeSelect所需的树形结构
      const buildTreeData = (items: any[]): any[] => {
        return items.map((item) => ({
          title: item.menu_name,
          value: item.id,
          key: item.id,
          selectable: true,
          children: item.children ? buildTreeData(item.children) : [],
        }));
      };

      // 添加一个根节点
      const treeData = [
        {
          title: "根菜单",
          value: 0,
          key: 0,
          children: buildTreeData(res.data),
        },
      ];

      setMenuTree(treeData);
    } catch (error) {
      console.error("获取菜单列表失败:", error);
      message.error("获取菜单列表失败");
    } finally {
      setLoading(false);
    }
  };

  // 获取所有权限
  const fetchPermissions = async () => {
    try {
      const res = await system.getPermissionAll();
      setPermissionOptions(res.data);
    } catch (error) {
      console.error("获取权限列表失败:", error);
      message.error("获取权限列表失败");
    }
  };

  // 添加菜单
  const handleAddMenu = () => {
    setModalTitle("添加菜单");
    form.resetFields();
    form.setFieldsValue({
      parent_id: 0,
      menu_type: "menu",
      visible: true,
      status: 1,
      sort_order: 0,
      is_fixed: false,
    });
    setIconPreview(null);
    setIsModalVisible(true);
  };

  // 编辑菜单
  const handleEditMenu = (record: any) => {
    setModalTitle("编辑菜单");
    form.resetFields();

    // 解析JSON字符串
    const permissions = record.permissions
      ? typeof record.permissions === "string"
        ? JSON.parse(record.permissions)
        : record.permissions
      : [];

    const user_types = record.user_types
      ? typeof record.user_types === "string"
        ? JSON.parse(record.user_types)
        : record.user_types
      : [];

    const role_types = record.role_types
      ? typeof record.role_types === "string"
        ? JSON.parse(record.role_types)
        : record.role_types
      : [];

    form.setFieldsValue({
      ...record,
      permissions,
      user_types,
      role_types,
    });

    if (record.icon) {
      setIconPreview(getIconByName(record.icon));
    } else {
      setIconPreview(null);
    }

    setIsModalVisible(true);
  };

  // 删除菜单
  const handleDeleteMenu = async (record: any) => {
    modal.confirm({
      title: `确定要删除菜单 [${record.menu_name}] 吗？`,
      content: "删除后，相关角色权限可能失效，请谨慎操作。",
      onOk: async () => {
        try {
          const res = await system.deleteMenu({ id: record.id });
          fetchMenuList();
        } catch (error) {
          console.error("删除菜单失败:", error);
        }
      },
    });
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const isUpdate = values.id !== undefined;

      // 提交请求
      const res: any = isUpdate
        ? await system.updateMenu(values)
        : await system.addMenu(values);

      setIsModalVisible(false);
      fetchMenuList();
    } catch (error) {
      console.error("表单提交失败:", error);
    }
  };

  // 监听菜单类型变化
  const handleMenuTypeChange = (value: string) => {
    if (value === "button") {
      form.setFieldsValue({
        component: null,
      });
    }
  };

  // 获取用户类型选项
  const getUserTypeOptions = () => {
    return [
      { label: "系统用户", value: "00" },
      { label: "机构用户", value: "01" },
    ];
  };

  return (
    <div className="h-full flex flex-col">
      <div className="flex flex-row justify-between items-center mb-4">
        <h3 className="text-lg font-semibold">菜单管理</h3>
        <Button type="primary" onClick={handleAddMenu}>
          添加菜单
        </Button>
      </div>

      <Card className="flex-1">
        <Table
          rowKey="id"
          columns={menuTableColumns(handleEditMenu, handleDeleteMenu)}
          dataSource={menuList}
          loading={loading}
          pagination={false}
          size="small"
          expandable={{
            defaultExpandAllRows: true,
          }}
          scroll={{ y: "calc(100vh - 280px)" }}
        />
      </Card>

      <Modal
        title={modalTitle}
        open={isModalVisible}
        onOk={handleSubmit}
        onCancel={() => setIsModalVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="parent_id" label="上级菜单" initialValue={0}>
                <TreeSelect
                  treeData={menuTree}
                  placeholder="请选择上级菜单"
                  showSearch
                  treeNodeFilterProp="title"
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="menu_name"
                label="菜单名称"
                rules={[{ required: true, message: "请输入菜单名称" }]}
              >
                <Input placeholder="请输入菜单名称" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="menu_key"
                label="菜单标识"
                rules={[{ required: true, message: "请输入菜单标识" }]}
              >
                <Input placeholder="唯一标识，如: system:user" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="menu_path"
                label="路由路径"
                rules={[{ required: true, message: "请输入路由路径" }]}
              >
                <Input placeholder="如: /system/user" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="菜单图标" name="icon" tooltip="请选择一个图标">
                <Select
                  placeholder="请选择图标"
                  allowClear
                  showSearch
                  onClear={() => setIconPreview(null)}
                  onChange={(iconName) => {
                    setIconPreview(getIconByName(iconName));
                  }}
                  filterOption={(input, option) =>
                    (option?.key as string)
                      ?.toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {Object.keys(IconMap).map((iconName) => (
                    <Option key={iconName} value={iconName}>
                      <div className="flex items-center">
                        <span className="mr-2">
                          {React.createElement(IconMap[iconName])}
                        </span>
                        <span>{iconName}</span>
                      </div>
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="menu_type"
                label="菜单类型"
                initialValue="menu"
                rules={[{ required: true, message: "请选择菜单类型" }]}
              >
                <Select
                  options={menuTypeOptions}
                  onChange={handleMenuTypeChange}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="sort_order"
                label="显示排序"
                initialValue={0}
                rules={[{ required: true, message: "请输入显示排序" }]}
              >
                <InputNumber min={0} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.menu_type !== currentValues.menu_type
            }
          >
            {({ getFieldValue }) =>
              getFieldValue("menu_type") === "menu" && (
                <Form.Item name="component" label="组件路径">
                  <Input placeholder="如: system/user/index" />
                </Form.Item>
              )
            }
          </Form.Item>

          <Divider orientation="left">权限配置</Divider>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="permissions" label="所需权限">
                <Select
                  mode="multiple"
                  placeholder="选择此菜单所需的权限"
                  options={permissionOptions}
                  filterOption={(input, option) =>
                    (option?.label ?? "")
                      .toLowerCase()
                      .includes(input.toLowerCase())
                  }
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="user_types" label="适用用户类型">
                <Select
                  mode="multiple"
                  placeholder="选择可以看到此菜单的用户类型"
                  options={getUserTypeOptions()}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="visible"
                label="菜单可见"
                valuePropName="checked"
                initialValue={true}
              >
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="status"
                label="菜单状态"
                valuePropName="checked"
                initialValue={true}
                getValueProps={(value) => ({ checked: value === 1 })}
                getValueFromEvent={(checked) => (checked ? 1 : 0)}
              >
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="is_fixed"
                label="固定菜单"
                valuePropName="checked"
                initialValue={false}
                tooltip="固定菜单不可删除"
              >
                <Switch />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default function MenuManagement() {
  return (
    <div className="h-full bg-white rounded-md p-4">
      <MenuPage />
    </div>
  );
}
